﻿// Write a program to convert decimal numbers to their hexadecimal representation.

using System;
using System.Text;

public class DecToHex
{
    static void Main()
    {
        Console.Write("Enter decimal number (or leave empty for Random): ");
        string decimalNumberString = Console.ReadLine();
        int decimalNumber;
        if (!int.TryParse(decimalNumberString, out decimalNumber) || string.IsNullOrEmpty(decimalNumberString))
        {
            Random random = new Random();
            decimalNumber = random.Next(int.MinValue, int.MaxValue);
            Console.WriteLine("Generated Random numbers is: {0}", decimalNumber);
        }

        Console.WriteLine("Hexadecimal representation is : {0}", ToHex(decimalNumber));
        Console.WriteLine("Hexadecimal number for control: {0}", decimalNumber.ToString("x").ToUpper());
    }

    public static string ToHex(int decimalNumber)
    {
        bool negative = false;
        if (decimalNumber < 0)
        {
            decimalNumber += int.MinValue;
            negative = true;
        }
        decimalNumber = Math.Abs(decimalNumber);

        StringBuilder hexNumberString = new StringBuilder();
        int remainder;
        while (decimalNumber > 0)
        {
            remainder = decimalNumber % 16;
            hexNumberString.Insert(0, GetSymbol(remainder));
            decimalNumber /= 16;
        }

        if (negative)
        {
            if (hexNumberString.Length < 8)
            {
                hexNumberString.Insert(0, '8');
            }
            else
            {
                int firstChar = ToNumber(hexNumberString[0]);
                char sum = GetSymbol(firstChar + 8);
                hexNumberString[0] = sum;
            }
        }

        return hexNumberString.ToString();
    }

    public static int ToNumber(char character)
    {
        int number = character - '0';
        if (number < 10)
        {
            return number;
        }

        return (int)character + 10 - 'A';
    }

    public static char GetSymbol(int number)
    {
        if (number > 9)
        {
            return (char)('A' + number - 10);
        }

        return (char)('0' + number);
    }
}